<template>
  <div class="table-box" v-loading="loading.value">
    <div class="top-buttons">
      <el-button type="primary" @click="loadData">搜索</el-button>
      <el-button type="primary" @click="onAddClick">新增</el-button>
    </div>
    <AgGrid
      ref="agGridRef"
      :columns="columns"
      v-model="list"
      @handle="onHandle"
    />
    <div class="bottom-buttons">
      <el-button type="success" @click="onSaveClick">保存</el-button>
      <el-button v-if="false" type="info">历史记录</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

import AgGrid from "@/components/ag-grid/index.vue";

import AgColumn from "@/bean/vo/AgColumn";
import TypeVO from "@/bean/vo/TypeVO";

import FieldApi from "@/api/setting/field";

import Loading from "@/utils/Loading";
import RecordApi from "@/api/record";

const props = defineProps<{
  typeId: number;
}>();

const $router = useRouter();

const agGridRef = ref<InstanceType<typeof AgGrid>>();

const columns = ref<AgColumn<TypeVO>[]>([
  {title: '操作', type: 'buttons', buttons: [
  ]},
]);

const loading = reactive(new Loading());

const list = ref<any[]>([]);

function onHandle(eventType: string, data: TypeVO) {
  if (eventType === 'delete') {
    onDeleteClick(data);
  }
  else if (eventType === 'view') {
    onViewClick(data);
  }
}

function loadColumns() {
  return loading.execute(async() => {
    const fieldInfos = await FieldApi.getList(props.typeId);
    const dyColumns = fieldInfos.map<AgColumn<TypeVO>>(item => ({
      title: item.displayName,
      field: item.name,
      type: item.renderType as any,
      editable: params => params.data.editables?.includes(params.colDef.field),
      options: params => params.data.optionsMap?.[params.colDef.field] || item.options,
    }));
    columns.value = [
      ...dyColumns,
      {title: '操作', type: 'buttons', buttons: [
        {title: '预览', type: 'primary', size: 'small', eventType: 'view'},
        {title: '删除', type: 'danger', size: 'small', eventType: 'delete'},
      ]},
    ];
  });
}

function loadData() {
  return loading.execute(async() => {
    list.value = await RecordApi.getList(props.typeId);
    agGridRef.value.clear();
  });
}

function onAddClick() {
  agGridRef.value.add();
}

function onSaveClick() {
  return loading.execute(async() => {
    await FieldApi.save(agGridRef.value.getSubmitRows());
    ElMessage.success('保存成功');
    await loadData();
  });
}

function onViewClick(data: TypeVO) {
  $router.push({
    path: `/view/${data.id}`
  });
}

function onDeleteClick(data: TypeVO) {
  agGridRef.value.remove(data);
}

onMounted(() => {
  loadColumns();
  loadData();
});
</script>

<style scoped>
.table-box {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.top-buttons {
  margin-bottom: 10px;
  text-align: right
}
.bottom-buttons {
  margin-top: 10px;
}
</style>
